"""
Case Type   : 资源池化集群系统内部使用工具
Case Name   : 主机上添加备份实例,未设置vgname
Create At   : 2024/04/19
Owner       : @kyleze
Description :
    1.主机上初始化目录
    2.主机上添加备份实例,未设置vgname
Expect      :
    1.成功
    2.失败,合理报错
History     :
"""

import os
import unittest

from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH

from yat.test import Node
from yat.test import macro


@unittest.skipIf(
    "dms_res" not in Common().get_sh_result(
    Node("PrimaryDbUser"), f"source {macro.DB_ENV_PATH}; "
    f"cm_ctl query -Cvidp"), "非资源池化环境不执行")
class SharedStorageGsProbackup(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)[:-3]} start-----")
        self.constant = Constant()
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.com = Common()
        self.pri_node = Node(node='PrimaryDbUser')
        self.parent_path = os.path.dirname(macro.DB_INSTANCE_PATH)
        self.backup_path = os.path.join(self.parent_path,
                                        "backupset/backup_dir_001")
        self.instance_name = 'probackup_003'
        self.log.info("-----检查数据库状态是否正常-----")
        status = self.primary_sh.get_db_cluster_status()
        self.assertTrue("Degraded" in status or "Normal" in status)
        cmd = f'source {macro.DB_ENV_PATH};' \
              f'cat $DSS_HOME/cfg/dss_vg_conf.ini |cut -d ":" -f 1'
        vgname_infor = self.pri_node.sh(cmd).result().strip()
        self.vgname = "+" + vgname_infor.split('\n')[0].strip() + \
                      ",+" + vgname_infor.split('\n')[1].strip()
        self.socket_path = self.com.show_param("ss_dss_conn_path")

    def test_gs_pro_backup(self):
        step = '--step1:主机上初始化目录 expect:成功--'
        self.log.info(step)
        result = self.primary_sh.exec_pro_backup_init(self.backup_path)
        self.log.info(result)
        self.assertTrue(result, "执行失败:" + step)

        step = '--step2:主机上添加备份实例,未设置vgname expect:失败,合理报错--'
        self.log.info(step)
        result = self.primary_sh.exec_pro_back_add(
            self.backup_path, self.instance_name,
            f"--enable-dss --instance-id 0 --socketpath='{self.socket_path}'",
            True)
        self.log.info(result)
        self.assertIn('ERROR: Vgname must be specified in dss mode',
                      result, "执行失败:" + step)

    def tearDown(self):
        clear_cmd = f"rm -rf {self.backup_path};"
        self.log.info(clear_cmd)
        clear_msg = self.pri_node.sh(clear_cmd).result()
        self.log.info(clear_msg)
        self.log.info(f"-----{os.path.basename(__file__)} end-----")

